package com.wfx.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayRequest;
import com.github.wxpay.sdk.WXPayUtil;
import com.jwt.pay.WeixinConfig;
import com.wfx.entity.Result;
import com.wfx.entity.WxbOrderItems;
import com.wfx.mapper.WxbOrderItemsMapper;
import com.wfx.service.IPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>title: com.wfx.service.impl</p>
 * author zhuximing
 * description:
 */
@Service
public class WxpayServiceImpl implements IPayService {
    @Autowired
    private WxbOrderItemsMapper wxbOrderItemsMapper;
    @Override
    public Result pay(String orderId) {
        //1：计算fee
        QueryWrapper<WxbOrderItems> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        List<WxbOrderItems> items = wxbOrderItemsMapper.selectList(queryWrapper);
        Integer fee = 0;
        for (WxbOrderItems item : items) {
            Double price = Double.parseDouble(item.getSkuPrice()) * 100;
            fee = fee + price.intValue() * item.getBuyNum();
        }
        //调用微信的统一下单接口
        try {
            String codeUrl = unifiedorder(orderId, 1, "http://wylp.free.idcfengye.com/weixin/notify");
            if (codeUrl == null) {
                return new Result(false,"下单失败");
            }
            //返回数据
            Map data = new HashMap();
            data.put("codeUrl",codeUrl);
            data.put("fee",fee);
            return  new Result(true,"下单成功",data);
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result(false,"下单失败");
        }
    }
    @Override
    public Result queryOrderStatus(String orderId) {

        try {
            return queryOrder(orderId);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"支付失败");
        }
    }

    private Result queryOrder(String orderId) throws  Exception{
        WeixinConfig config = new WeixinConfig();
        //封装请求参数
        Map reqeustParams = new HashMap();
        reqeustParams.put("appid",config.getAppID());
        reqeustParams.put("mch_id",config.getMchID());
        reqeustParams.put("nonce_str", WXPayUtil.generateNonceStr());
        reqeustParams.put("out_trade_no", orderId);
        //将map转换成xml数据格式
        String xmlParams = WXPayUtil.generateSignedXml(reqeustParams, config.getKey());
        //发请求
        WXPayRequest request = new WXPayRequest(config);
        String xmlRes = request.requestWithoutCert("/pay/orderquery", UUID.randomUUID().toString(),
            xmlParams, false);
        System.out.println(xmlRes);
        //将xml结果转换成map
        Map<String, String>  mapRes = WXPayUtil.xmlToMap(xmlRes);
        /**
         * SUCCESS--支付成功
         * REFUND--转入退款
         * NOTPAY--未支付
         * CLOSED--已关闭
         * REVOKED--已撤销(刷卡支付)
         * USERPAYING--用户支付中
         * PAYERROR--支付失败(其他原因，如银行返回失败)
         * ACCEPT--已接收，等待扣款
         * 支付状态机请见下单API页面
         */
        System.out.println("trade_state=="+ mapRes.get("trade_state"));
        if ("SUCCESS".equals(mapRes.get("trade_state"))) {
            return new Result(true,"支付成功");
        }
        return new Result(false,"支付失败");

    }
    private String unifiedorder(String orderId,Integer fee,String notifyUrl) throws Exception {
        //调用统一下单接口
        WeixinConfig config = new WeixinConfig();
        //封装请求参数
        Map reqeustParams = new HashMap();
        reqeustParams.put("appid", config.getAppID());
        reqeustParams.put("mch_id", config.getMchID());
        reqeustParams.put("nonce_str", WXPayUtil.generateNonceStr());
        reqeustParams.put("body", "微分销项目");
        reqeustParams.put("out_trade_no", orderId);
        reqeustParams.put("total_fee",  fee+ "");
        reqeustParams.put("spbill_create_ip", "127.0.0.1");
        reqeustParams.put("notify_url", notifyUrl);
        reqeustParams.put("trade_type", "NATIVE");
        //将map转换成xml数据格式
        String xmlParams = WXPayUtil.generateSignedXml(reqeustParams, config.getKey());
        //发请求
        WXPayRequest request = new WXPayRequest(config);
        String xmlRes = request.requestWithoutCert("/pay/unifiedorder", UUID.randomUUID().toString(),
            xmlParams, false);
        System.out.println(xmlRes);
        //将xml结果转换成map
        Map<String, String> mapRes = WXPayUtil.xmlToMap(xmlRes);
        System.out.println("code_url==" + mapRes.get("code_url"));
        return  mapRes.get("code_url");
    }
}